# !/usr/bin/python3
# -*- coding:utf-8 -*-
# Copyright 2021 The Chinaunicom Software Team.
# @FileName: cda_server.py
# @Author  : Dammy
# @Time    : 2021/12/14

from flask import Flask, jsonify, request
import numpy as np
import time
import json
from nlpcda import Simbert
from msg_conf import config
# import predict

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = True


### 预加载 ###
# SimBERT
model_path = 'chinese_simbert_L-6_H-384_A-12'
# SimBERTv2
model_path_ro = '/home/bml/storage/NLG/chinese_roformer-sim-char_L-12_H-768_A-12'
  
model_config = {
    'model_path': model_path,
    'CUDA_VISIBLE_DEVICES': '0',
    'max_len': 32, 
    'seed': 1,
}
sim_bert = Simbert(config=model_config)

# query = {"question":"xxxxxxx", "nums":10}


def check_param(post_json):
    """
    字段检测，key是否存在，类型是否正常等
    """
    # 1. 核对字段是否符合要求
    if 'question' not in post_json:
        return False
    else:
        return True


@app.route('/question_generator_server', methods=['POST'])
def question_generator_server():
    """
    Main Interface Route
    :return:
    """
    # log_server.logging('============Enter Generate similar question System !===========')
    result_format = {'STATUS': config['RETURN_STATUS']['OK'], 'MSG': config['RETURN_MSG']['OK'], 'synonyms': list()}

    try:
        post_data = request.data
        # 数据编码校验
        if isinstance(post_data, bytes):
            post_data = post_data.decode()
        query_json = json.loads(post_data)
    except Exception as e:
        result_format['STATUS'] = config['RETURN_STATUS']['URL_ERROR']
        result_format['MSG'] = config['RETURN_MSG']['URL_ERROR']
        return jsonify(result_format)

    # step1: 数据格式校验
    if not check_param(query_json):
        result_format['STATUS'] = config['RETURN_STATUS']['PARAMETERS_ERROR']
        result_format['MSG'] = config['RETURN_MSG']['PARAMETERS_ERROR']
        return jsonify(result_format)

    # step2: 预测
    pre_start = time.time()
    try:
        synonyms = sim_bert.replace(sent=query_json['question'], create_num=query_json['nums'])
    except Exception as e:
        result_format['RSP_CODE'] = config['RETURN_RSP_CODE']['CONNTECTION_TIMEOUT']
        result_format['RSP_DESC'] = config['RETURN_RSP_DESC']['CONNTECTION_TIMEOUT']
        return jsonify(result_format)

    pre_end = time.time()
    result_format['synonyms'] = synonyms
    # log_server.logging('>>>>>>>> Time of the whole process: {:.6f}'.format(pre_end - pre_start))
    # log_server.logging('============Exit SQR System !===========')
    return jsonify(result_format)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=10000)
    # app.run()



